"""
@author: xxw
@file: music_api.py.py
@time: 2023/7/31 20:58
"""
from flask import request

from libs.auth import auth_required
from libs.handler import default_error_handler
from libs.response import generate_response
from . import product_bp
from flask_restful import Api, Resource
from models.product import Song
from models import db

# 将restful api 对象和蓝图绑定
api = Api(product_bp)
api.handle_error = default_error_handler

class MusicView(Resource):
    @auth_required
    def get(self, id=None):
        if id == None:
            data = Song.query.all()
        else:
            data = Song.query.filter(Song.id == id).all()
        if data:
            # 序列化  json -- pickle
            # 让对象可以跨平台存储或者进行网络传输
            # 自定义实现
            # data_dict = [convert_to_dict(item) for item in data]

            # 可以通过dict函数将对象变为字典。 对象要实现keys 和 __getitem__的方法
            result = [dict(pro) for pro in data]
            return generate_response(data=result, message="get product info success!")
        else:
            return generate_response(message="get data empty!", code=5)
    def post(self):
        _name = request.json.get("songname")
        _singer = request.json.get("singer")
        _duration = request.json.get("duration")
        _kind = request.json.get("kind")
        songinfo = Song(song_name=_name,
                              singer=_singer,
                              duration=_duration,
                              kind=_kind
                              )
        # 提交数据库
        db.session.add(songinfo)
        db.session.commit()
        return generate_response(message="add_product")
    def put(self, id):
        songinfo = Song.query.get(id)
        if songinfo:
            _name = request.json.get("songname")
            _singer = request.json.get("singer")
            _duration = request.json.get("duration")
            _kind = request.json.get("kind")

            songinfo.song_name = _name
            songinfo.singer = _singer
            songinfo.duration = _duration
            songinfo.kind = _kind

            db.session.add(songinfo)
            db.session.commit()
            return generate_response(message="modify success!")
        else:
            return generate_response(message="no that id!")
    def delete(self, id):
        songinfo = Song.query.get(id)
        db.session.delete(songinfo)
        db.session.commit()
        return generate_response(message="delete success!")

api.add_resource(MusicView, "/music")
api.add_resource(MusicView, "/music/<id>", endpoint="musicid")